package org.jeecg.modules.system.controller;

import org.apache.commons.io.FileUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.entity.TChunkInfo;
import org.jeecg.modules.system.entity.TFileInfoVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/api/upload")
public class UploadController {
    private static String FILENAME = "";
    @Value("${YouZ.upload.file.path}")
    private String decryptFilePath;
    @Value("${YouZ.upload.file.temp}")
    private String decryptFilePathTemp;
    /**
     * 上传文件块
     * @param chunk
     * @return
     */
    @PostMapping("/chunk")
    public String uploadChunk(TChunkInfo chunk) throws IOException {
        String apiRlt = "200";
        MultipartFile file = chunk.getUpfile();
        String guid = chunk.getIdentifier();
        Integer chunkNumber = chunk.getChunkNumber();
        System.out.println("guid:" + guid);
        File outFile = new File(decryptFilePathTemp+File.separator+guid, chunkNumber + ".part");
        if ("".equals(FILENAME)) {
            FILENAME = chunk.getFilename();
        }
        InputStream inputStream = file.getInputStream();
        FileUtils.copyInputStreamToFile(inputStream, outFile);
        return apiRlt;
    }

    @PostMapping("/mergeFile")
    public Result mergeFile(@RequestBody TFileInfoVO fileInfoVO) throws Exception{
        String rlt = "FALURE";
        String guid = fileInfoVO.getUniqueIdentifier();
        System.out.println("merge:"+guid);
        File file = new File(decryptFilePathTemp+File.separator+guid);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                File partFile = new File(decryptFilePath + File.separator + FILENAME);
                for (int i = 1; i <= files.length; i++) {
                    File s = new File(decryptFilePathTemp+File.separator+guid, i + ".part");
                    FileOutputStream destTempfos = new FileOutputStream(partFile, true);
                    FileUtils.copyFile(s,destTempfos );
                    destTempfos.close();
                }
                FileUtils.deleteDirectory(file);
                FILENAME = "";
                rlt = "SUCCESS";
            }
        }

        return Result.OK("http://106.12.160.17/static/"+fileInfoVO.getName());
    }

}
